package com.gzsxy.JUC.pc;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 线程之间的通信问题：生产者和消费者问题！
 * 线程交替执行 a b 操作同一个变量 num = 0
 * JUC模式    lock condition.await()    condition.signalAll();
 */
public class B {
    public static void main(String[] args) {
        Data data = new Data();
        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                try {
                    data.increment();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

            }
        }, "A").start();

        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                try {
                    data.decrement();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

            }
        }, "B").start();

        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                try {
                    data.increment();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

            }
        }, "C").start();

        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                try {
                    data.decrement();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

            }
        }, "D").start();

    }
}

class Data1 {
    private int number = 0;
    //创建锁对象 ===公平锁与非公平锁
    Lock lock = new ReentrantLock();
    //通过newCondition去等待，提醒其他线程
    Condition condition = lock.newCondition();

    //+1
    public void increment() throws InterruptedException {

        //开启锁
        lock.lock();
        //如果这里用if判断那么在多个线程当中进来这个方法，if只判断一次，
        try {
            while (number != 0) {
                //等待
                condition.await();

            }
            number++;
            //通知其他线程，我+1完毕了
            System.out.println(Thread.currentThread().getName() + "=>" + number);
            //通过其他线程我+1完毕
            condition.signalAll();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            //关闭锁
            lock.unlock();
        }
    }


    //-1
    public void decrement() throws InterruptedException {
        while (number == 0) {
            //等待
            condition.await();


        }
        number--;
        //通知其他线程，我-1完毕了
        System.out.println(Thread.currentThread().getName() + "=>" + number);
        //通过其他线程我-1完毕
        condition.signalAll();
    }


}